package ltd.sumfsy.grain.service.impl;

import ltd.sumfsy.grain.bean.RelationUserAndEquip;
import ltd.sumfsy.grain.bean.example.RelationUserAndEquipExample;
import ltd.sumfsy.grain.mapper.RelationUserAndEquipMapper;
import ltd.sumfsy.grain.service.RelationUserAndEquipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户和设备之间联系相关的服务实现类
 * @author 范颂扬
 * @create 2021-05-13 9:48
 */
@Service
public class RelationUserAndEquipServiceImpl implements RelationUserAndEquipService {

    private final RelationUserAndEquipMapper relationMapper;

    @Autowired
    public RelationUserAndEquipServiceImpl(RelationUserAndEquipMapper relationMapper) {
        this.relationMapper = relationMapper;
    }

    @Override
    public boolean bind(RelationUserAndEquip relation) {
        int res = relationMapper.insertSelective(relation);
        return res > 0;
    }

    @Override
    public boolean unBind(RelationUserAndEquip relation) {
        RelationUserAndEquipExample example = new RelationUserAndEquipExample();
        example.createCriteria()
                .andUserIdEqualTo(relation.getUserId())
                .andEquipIdEqualTo(relation.getEquipId());
        int res = relationMapper.updateByExampleSelective(relation.setDelFlag(1), example);
        return res > 0;
    }

    @Override
    public List<RelationUserAndEquip> queryAll() {
        RelationUserAndEquipExample example = new RelationUserAndEquipExample();
        example.createCriteria().andDelFlagEqualTo(0);
        return relationMapper.selectByExample(example);
    }

    @Override
    public List<Integer> queryByUserId(Integer userId) {
        RelationUserAndEquipExample example = new RelationUserAndEquipExample();
        example.createCriteria().andUserIdEqualTo(userId).andDelFlagEqualTo(0);
        List<RelationUserAndEquip> relations = relationMapper.selectByExample(example);
        List<Integer> equipIds = new ArrayList<>();
        for (RelationUserAndEquip relation: relations) {
            equipIds.add(relation.getEquipId());
        }
        return equipIds;
    }

    @Override
    public List<Integer> queryByEquipId(Integer equipId) {
        RelationUserAndEquipExample example = new RelationUserAndEquipExample();
        example.createCriteria().andEquipIdEqualTo(equipId).andDelFlagEqualTo(0);
        List<RelationUserAndEquip> relations = relationMapper.selectByExample(example);
        List<Integer> userIds = new ArrayList<>();
        for (RelationUserAndEquip relation: relations) {
            userIds.add(relation.getUserId());
        }
        return userIds;
    }
}
